package com.wlcb.jpower.chat.reply.handler.fixed;

import com.wlcb.jpower.chat.entity.customer.TblCustomerMsg;
import com.wlcb.jpower.chat.reply.ReplyHandler;
import com.wlcb.jpower.chat.reply.ReplyEntity;
import com.wlcb.jpower.chat.service.customer.CustomerMsgService;
import com.wlcb.jpower.chat.service.customer.SpecialUserService;
import com.wlcb.jpower.constant.DBConstant;
import com.wlcb.jpower.im.cache.ImChatRecordCache;
import com.wlcb.jpower.im.model.DataPacket;
import com.wlcb.jpower.module.common.utils.Fc;
import com.wlcb.jpower.module.common.utils.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;

import java.util.List;

/**
 * @author: liwenfei
 * @version: v1.0
 * @time: 2021/3/3 15:44
 * @desc: 客服退出  该回复不暴露给用户
 */
@Slf4j
public class QuitReplyHandler extends ReplyHandler {
    private static CustomerMsgService customerMsgService;

    static {
        customerMsgService = SpringUtil.getBean(CustomerMsgService.class);
    }

    @Override
    public ReplyEntity handler(DataPacket dataPacket, WxMpXmlMessage wxMessage) {
        log.debug("进入客服退出回复");
        SpecialUserService specialUserService = SpringUtil.getBean(SpecialUserService.class);
        if (specialUserService.findByOpenidAndAppid(dataPacket.getSendId(), dataPacket.getAppId()) == null) {
            return ReplyEntity.singleTextMessage("", false);
        }
        TblCustomerMsg tblCustomerMsg = customerMsgService.findbyAppIdAndOpenid(dataPacket.getAppId(), dataPacket.getSendId());
        if (!Fc.isNull(tblCustomerMsg)) {
            ImChatRecordCache imChatRecordCache = ImChatRecordCache.getInstance(wxMessage.getFromUser());
            List<DataPacket> records = imChatRecordCache.getRecords();
            tblCustomerMsg.setData(records.toString());
            tblCustomerMsg.setStatus(DBConstant.CustomerMsgEnum.USER_QUIT.getType());
            customerMsgService.modifyById(tblCustomerMsg);
            imChatRecordCache.remove();
            ReplyEntity kefu = ReplyEntity.singleTextMessage("退出成功", true).kefu();
            kefu.setAppId(dataPacket.getAppId());
            kefu.setToUser(wxMessage.getFromUser());
            return kefu;
        }
        return null;
    }

    @Override
    public ReplyEntity handler(DataPacket dataPacket, WxMpXmlMessage wxMessage, ImChatRecordCache cache) {
        return null;
    }
}
